package com.isoft.farm.service.Impl;

import com.isoft.farm.common.PageObject;
import com.isoft.farm.common.ServiceException;
import com.isoft.farm.dao.SysUserDao;
import com.isoft.farm.dao.SysUserRoleDao;
import com.isoft.farm.entity.SysUser;
import com.isoft.farm.entity.SysUserDeptVo;
import com.isoft.farm.service.SysUserService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserDao sysUserDao;
    @Autowired
    SysUserRoleDao sysUserRoleDao;

    @Override
    public boolean doLogin(String username, String password) {
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        sysUser.setPassword(password);
        int row = sysUserDao.findSysUser(sysUser);
        if (row > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean doReg(SysUser sysUser) {
        sysUser.setValid("0");
        sysUser.setCreatedTime(new Date());
        int row = sysUserDao.insertSysUser(sysUser);
        if (row > 0) {
            return true;
        }
        return false;
    }

    @Override
    public PageObject<SysUserDeptVo> findPageObjects(String username, Integer pageCurrent) {
        if (pageCurrent == null || pageCurrent < 1)
            throw new IllegalArgumentException("当前页码无效");
        int rowcount = sysUserDao.getRowCount(username);
        if (rowcount == 0)
            throw new ServiceException("没有找到对应记录");
        int pageSize = 5;
        int startIndex = (pageCurrent - 1) * pageSize;
        List<SysUserDeptVo> records = sysUserDao.findPageObject(username, startIndex, pageSize);

        return new PageObject<>(pageCurrent, pageSize, rowcount, records);
    }

    public int validById(Integer id, Integer valid, String modifiedUser) {
        if (id == null || id <= 0)
            throw new IllegalArgumentException("参数不合法, id=" + id);
        if (valid != 1 && valid != 0)
            throw new IllegalArgumentException("参数不合法, valid=" + valid);
        if (StringUtils.isEmpty(modifiedUser))
            throw new ServiceException("修改用户名不能为空！");
        //更改状态
        int row = sysUserDao.validById(id, valid, modifiedUser);
        //验证返回值
        if (row == 0)
            throw new ServiceException("此纪录可能不存在！");
        return row;
    }

    @Override
    public int saveObject(SysUser sysUser, Integer[] roleIds) {
        if (sysUser == null)
            throw new IllegalArgumentException("保存对象不能为空");
        if (StringUtils.isEmpty(sysUser.getUsername()))
            throw new IllegalArgumentException("用户名不能为空");
        if (StringUtils.isEmpty(sysUser.getPassword()))
            throw new IllegalArgumentException("密码不能为空");
        if (roleIds == null || roleIds.length == 0)
            throw new IllegalArgumentException("至少要为用户分配一个角色");

        //插入用户
        //将密码加密，再插入
        String source=sysUser.getPassword();
        String salt= UUID.randomUUID().toString();
        SimpleHash simpleHash=new SimpleHash(
                "MD5",
                source,
                salt,
                1
        );
        sysUser.setSalt(salt);
        sysUser.setPassword(simpleHash.toHex());//去除加密以后的密码
        //创建时间，创建用户的设置
        sysUser.setCreatedTime(new Date());
        sysUser.setCreatedUser("admin");
        //插入用户
        int rows=sysUserDao.insertSysUser(sysUser);
        sysUserRoleDao.insertObjects(sysUser.getId(),roleIds);
        return rows;
    }

    @Override
    public Map<String, Object> findObjectById(Integer userId) {
        //验证参数
        if(userId==null||userId<=0)
            throw new IllegalArgumentException("参数不合法，userId="+userId);
        //业务查询
        //查询用户自己的信息
        SysUserDeptVo sysUserDeptVo=sysUserDao.findObjectById(userId);
        if (sysUserDeptVo==null)
            throw new ServiceException("此用户不存在");
        //查询用户角色的信息
        List<Integer> roleIds=sysUserRoleDao.findRoleIdByUserId(userId);
        //数据封装
        Map<String,Object> map=new HashMap<>();
        map.put("user",sysUserDeptVo);
        map.put("roleIds",roleIds);
        return map;
    }

    @Override
    public int updateObject(SysUser sysUser, Integer[] roleIds) {
        if (sysUser==null)throw new IllegalArgumentException("修改的对象不能为空");
        if (StringUtils.isEmpty(sysUser.getUsername())){
            throw new IllegalArgumentException("用户名称不能为空!");
        }
        if (roleIds==null||roleIds.length==0)
            throw new IllegalArgumentException("至少要为用户分配一个角色");
        //修改自身信息
        int row=sysUserDao.updateObject(sysUser);
        //对角色的操作 删除 后添加
        sysUserRoleDao.deleteObjectsByUserId(sysUser.getId());
        sysUserRoleDao.insertObjects(sysUser.getId(),roleIds);
        return row;
    }
}
